package org.spbsu.apco.server;

import org.spbsu.apco.common.data.core.DurationEstimable;
import org.spbsu.apco.common.task.core.BaseTask;
import org.spbsu.apco.common.task.core.Ticket;
import org.spbsu.apco.server.scheduler.BaseScheduler;
import org.spbsu.apco.server.taskset.BaseTaskSet;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * User: ortemij
 * Date: 06.01.13
 * Time: 0:12
 */
public abstract class TaskSetTestCase {

    protected final List<BaseTask> leafTasks = new ArrayList<BaseTask>();
    protected ConcatenateStringTask task1;
    protected ConcatenateStringTask task2;
    protected BaseTaskSet taskSet;

    public void init() {
        for (int i = 0; i < 10; i++) {
            final EchoStringTask commandLineTask = new EchoStringTask();
            leafTasks.add(commandLineTask);
        }

        task1 = new ConcatenateStringTask(leafTasks.subList(0, 5));
        task2 = new ConcatenateStringTask(leafTasks.subList(5, 10));

        taskSet = new BaseTaskSet() {
            @Override
            public void initializeTasks() {
                for (int i = 0; i < 10; i++) {
                    addLeafTask(leafTasks.get(i), Arrays.asList("" + i));
                }
                addTask(task1);
                addTask(task2);
            }
        };
    }

    public static class ConcatenateStringTask extends BaseTask<String, String> implements DurationEstimable<String> {

        private ConcatenateStringTask(List<BaseTask> subTasks) {
            super(subTasks);
        }

        @Override
        public String execute(final List<String> inputData) throws Exception {
            StringBuilder sb = new StringBuilder();
            for (String s : inputData) {
                sb.append(s);
            }
            return sb.toString();
        }

        @Override
        public int estimateDuration(List<String> inputData) {
            return 250;
        }
    }

    public static class EchoStringTask extends BaseTask<String, String> implements DurationEstimable<String> {

        @Override
        public String execute(final List<String> inputData) throws Exception {
            return inputData.get(0);
        }

        @Override
        public int estimateDuration(List<String> inputData) {
            return 100;
        }
    }

    public static class MockedScheduler extends BaseScheduler {
        @Override
        protected Ticket getTicketFor(String clientId) {
            final Collection<Ticket> ready = getReadyForExecutionTickets();
            return ready.isEmpty() ? null : ready.iterator().next();
        }
    }
}
